"use strict";

module.exports = core;

const pkg = require("../package.json");
const log = require("@zkc-cli-dev/log");
const semver = require("semver");
const colors = require("colors");
const constant = require("./const");
const rootCheck = require("root-check");
const userHome = require("user-home");
const pathExists = require("path-exists").sync;

function core() {
  try {
    // 检查版本号
    checkPkgVersion();
    // 检查node版本号
    checkNodeVersion();
    // 检查是否是root权限
    checkRoot();
    // 检查是否主目录
    checkUserHome();
    // 检查参数
    checkInputArgs();
    log.verbose("debug", "test");
  } catch (error) {
    log.error(error.message);
  }
}

function checkInputArgs() {
  const minimist = require("minimist");
  const args = minimist(process.argv.slice(2));
  if (args.debug) {
    // process.env.LOG_LEVEL = "verbose";
  } else {
    process.env.LOG_LEVEL = "info";
  }
  log.level = process.env.LOG_LEVEL;
}

function checkArgs() {}

function checkUserHome() {
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red("当前登录用户主目录不存在"));
  }
}

function checkRoot() {
  rootCheck();
}

function checkNodeVersion() {
  const currentNodeVersion = process.version;
  const lowestNodeVersion = constant.LOWEST_NODE_VERSION;
  if (!semver.gte(currentNodeVersion, lowestNodeVersion)) {
    throw new Error(
      colors.red(`zkc-cli 需要安装 v${lowestNodeVersion} 已上版本的 Node.js`)
    );
  }
}

function checkPkgVersion() {
  log.notice("cli", pkg.version);
}
